<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace app\commands;

use app\models\Article;
use app\models\Feed;
use app\models\Job;
use app\models\JobArticle;
use app\models\Tag;
use app\models\User;
use app\models\UserGroup;
use Yii;
use yii\console\Controller;
use yii\console\ExitCode;

/**
 * This command echoes the first argument that you have entered.
 *
 * This command is provided as an example for you to learn how to create console commands.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class HelloController extends Controller
{
    /**
     * This command echoes what you have entered as the message.
     * @param string $message the message to be echoed.
     * @return int Exit code
     */
    public function actionIndex($message = 'hello world')
    {
        echo $message . "\n";

        return ExitCode::OK;
    }

    public function actionImportJob(){
        $fileName = Yii::$app->basePath.'/runtime/files/职业表(3).xls';
        $data = \moonland\phpexcel\Excel::import($fileName, [
            'setFirstRecordAsKeys' => false,
            'setIndexSheetByName' => false,
            'getOnlySheet' => 'Sheet1',
        ]);

        User::updateAll(['job_id'=>0]);
        JobArticle::deleteAll();
        Yii::$app->db->createCommand()->truncateTable('job')->execute();
        foreach ($data as $v){
            foreach ($v as $v2){
                if(!$v2 || !trim($v2)){
                    continue;
                }
                list($one, $two, $three) = explode('/', $v2);
                $one_m = Job::findOne(['name'=>$one]);
                if(!$one_m){
                    $one_m = new Job();
                    $one_m->name = $one;
                    $one_m->save();
                }
                $two_m = Job::findOne(['name'=>$two, 'pid'=>$one_m->id]);
                if(!$two_m){
                    $two_m = new Job();
                    $two_m->name = $two;
                    $two_m->pid  = $one_m->id;
                    $two_m->save();
                }
                $three_m = Job::findOne(['name'=>$three, 'pid'=>$two_m->id]);
                if(!$three_m){
                    $three_m = new Job();
                    $three_m->name = $three;
                    $three_m->pid  = $two_m->id;
                    $three_m->save();
                }
            }
        }
    }

    public function actionImportUser(){
        $fileName = Yii::$app->basePath.'/runtime/files/用户列表1113.xlsx';
        $data = \moonland\phpexcel\Excel::import($fileName, [
            'setFirstRecordAsKeys' => true,
            'setIndexSheetByName' => false,
            'getOnlySheet' => 'Sheet1',
        ]);
        $gender_map = [
            null => User::UNKNOWN,
            '' => User::UNKNOWN,
            '无' => User::UNKNOWN,
            '男' => User::MALE,
            '女' => User::FEMALE,
        ];
        $type_map = [
            null  => User::COMMON,
            ''  => User::COMMON,
            '普通' => User::COMMON,
            '订阅号' => User::SUBSCRIPTION,
            '企业号' => User::COMPANY,
            '大佬' => User::VIRTUAL,
            '管理员' => User::ADMIN
        ];
        $vest_map = [
            null => User::VEST,
            '' => User::VEST,
            '是' => User::VEST,
            '否' => User::NO_VEST,
        ];
        foreach ($data as $v){
            $username = trim($v['用户名']);
            $password = trim($v['密码']);
            $nickname = trim($v['昵称']);
            $gender = trim($v['性别']);
            $sign = trim($v['签名']);
            $type = trim($v['用户类型']);
            $vest = trim($v['马甲']);
            if(!User::find()->where(['username'=>$username, 'type'=>$type_map[$type]])->exists()){
                $user = new User();
                $user->username = $username;
                $user->password = Yii::$app->security->generatePasswordHash($password);
                $user->nickname = $nickname;
                $user->gender   = $gender_map[$gender];
                $user->sign     = $sign;
                $user->type = $type_map[$type];
                $user->vest = $vest_map[$vest];
                $user->save();
            }
        }
    }

    public function actionImportVirtualUser(){
        User::updateAll(['status'=>User::STATUS_DEL], ['type'=>User::VIRTUAL]);
        $fileName = Yii::$app->basePath.'/runtime/files/企业大佬列表修改.xlsx';
        $data = \moonland\phpexcel\Excel::import($fileName, [
            'setFirstRecordAsKeys' => true,
            'setIndexSheetByName' => false,
            'getOnlySheet' => 'Sheet1',
        ]);
        $gender_map = [
            null => User::UNKNOWN,
            '' => User::UNKNOWN,
            '无' => User::UNKNOWN,
            '男' => User::MALE,
            '女' => User::FEMALE,
        ];
        foreach ($data as $v){
            $nickname = trim($v['昵称']);
            $gender = trim($v['性别']);
            $sign   = trim($v['签名']);
            $group_name = trim($v['用户组名']);
            /** @var User $exist_user */
            $exist_user = User::find()->where(['nickname'=>$nickname, 'sign'=>$sign])->one();
            if(!$exist_user){
                $group = UserGroup::findOne(['name'=>$group_name]);
                if(!$group){
                    $group = new UserGroup();
                    $group->name = $group_name;
                    $group->save();
                }
                $user = new User();
                $user->nickname = $nickname;
                $user->gender   = $gender_map[$gender];
                $user->sign     = $sign;
                $user->type     = User::VIRTUAL;
                $user->vest     = User::VEST;
                $user->group_id = $group->id;
                if($user->save()){
                    echo $user->showNickname()."用户已保存\n";
                }
            }else{
                if($exist_user->status == User::STATUS_DEL){
                    $exist_user->status = User::STATUS_PASS;
                    $exist_user->save();
                    echo $nickname."：同签名的该昵称用户已恢复数据\n";
                }else{
                    echo $nickname."：同签名的该昵称用户已存在\n";
                }
            }
        }
    }

    /**
     * 修复用户组统计数据
     */
    public function actionRepairUserGroup(){
        /** @var UserGroup[] $groups */
        $groups = UserGroup::find()->all();
        foreach ($groups as $v){
            $v->user_num = User::find()->where(['group_id'=>$v->id, 'status'=>User::STATUS_PASS])->count();
            $v->save();
        }
    }

    public function actionRepairArticleNum(){
        /** @var Article[] $articles */
        $articles = Article::find()->where('like_num != 0')->all();
        foreach ($articles as $v){
            $v->repairSelf();
        }
    }

    public function actionRepairUser(){
        /** @var User[] $user */
        $user = User::find()->all();
        foreach ($user as $v){
            $v->repairSelf();
        }
    }

    public function actionRepairFeed(){
        Feed::deleteAll([
            'type'      => Feed::ARTICLE,
            'target_id' => Article::find()->where('status != :pass', [':pass'=>Article::STATUS_PASS])->select('id')->column()
        ]);
    }

    public function actionRepairImgDomain(){
        /** @var Article[] $list */
        $list = Article::find()
            ->where(['like', 'attach', 'phz035573.bkt.clouddn.com'])
            ->all();
        foreach ($list as $v){
            $v->attach = str_replace('phz035573.bkt.clouddn.com', 'img.cyjxy.com', $v->attach);
            $v->save();
        }
    }

    public function actionAddTagIdToPost(){
        $ids = Tag::find()->where(['type'=>Tag::TOPIC])->select('id')->column();
        /** @var Article[] $list */
        $list = Article::find()->where(['type'=>Article::TINY_POST])->all();
        foreach ($list as $v){
            $v->tag_id = $ids[rand(0, count($ids) - 1)];
            $v->save();
        }
    }

    public function actionRepairNickname(){
        $users = User::findAll(['type'=>User::COMMON]);
        foreach ($users as $v) {
            $v->nickname = $v->showNickname();
            $v->save();
        }
    }

    public function actionRepairUserFollow(){
        /** @var \app\models\UserFollowRecord[] $list */
        $list = \app\models\UserFollowRecord::find()->where(['date'=>0])->all();
        foreach ($list as $v){
            $v->date = strtotime(date('Y-m-d', $v->created_at));
            $v->save();
        }
    }

}
